package durst.data.json; 

import java.sql.SQLException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.mapper.helper.SimpleMapperHelper;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONValue;

import durst.data.Account;
import durst.data.dao.DaoFactory;

public class AccountJSONHelper implements SimpleMapperHelper {
	@Override
	public Class<Account> getHelpedClass() {
		return Account.class;
	}

	@Override
	public JSONValue toJSON(Object aPojo) throws MapperException {
		if (aPojo instanceof Account && aPojo != null) {
			Account acc = (Account)aPojo;
			
			if (acc.getUsername() == null)
				try {
					DaoFactory.getInstance().createDao(Account.class).refresh(acc);
				} catch (SQLException e) {
					throw new MapperException("could not refresh Account object from DB!");
				}
			
			JSONObject ret = new JSONObject();
			ret.getValue().put("id", JSONMapper.toJSON(acc.getId()));
			ret.getValue().put("username", JSONMapper.toJSON(acc.getUsername()));
			ret.getValue().put("fullname", JSONMapper.toJSON(acc.getFullName()));
			
			return ret;
		}
		
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object toJava(JSONValue aValue, Class aRequestedClass) throws MapperException {
		// We won't be using this functionality
		return null;
	}

}
